package com.oltpbenchmark.remote;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestfulCaller {
  String hostPort = null;

  public RestfulCaller(String hostPort) {
    this.hostPort = hostPort;
  }

  //get方式请求
  public String restCallerGet(String path, String param) {
    //path 接口路径 xxx/xxx/xxx
    //param 入参 ?xxx=x&xxx=x&xxx=x

    String data = "";

    //url拼接
    String lasturl = this.hostPort + path + param;
    try {
      URL url = java.net.URI.create(lasturl).toURL();
      //打开和url之间的连接
      HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

      //请求头
      urlConn.setRequestProperty("Accept-Charset", "utf-8");
      urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

      urlConn.setDoOutput(true);
      urlConn.setDoInput(true);
      urlConn.setRequestMethod("GET");//GET和POST必须全大写
      urlConn.connect();

      int code = urlConn.getResponseCode();//获得响应码
      if (code == 200) {//响应成功，获得响应的数据
        //InputStream is = urlConn.getInputStream();//得到数据流（输入流）
        //byte[] buffer = new byte[1024];
        //int length = 0;
        //while ((length = is.read(buffer)) != -1) {
        //	String res = new String(buffer, 0, length);
        //	data += res;
        //}
        //System.out.println(data);

        //解决中文乱码
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
        //data = reader.readLine();

        //解决返回参数换行问题，一次读一行，读入null时文件结束
        int line = 1;
        String tempString = null;
        while ((tempString = reader.readLine()) != null) {
          data += tempString;
          //把当前行号显示出来
          //System.out.println("line " + line + ": " + tempString);
          line++;
        }
        reader.close();

      }
      urlConn.disconnect();   //断开连接

    } catch (Exception e) {
      e.printStackTrace();
    }

    return data;
  }

  //post方式请求
  public String restCallerPost(String path, String param) {
    //path 接口路径 xxx/xxx/xxx
    //param 入参json {}

    int responseCode;
    //String urlParam = "?aaa=1&bbb=2";
    String urlParam = "";

    String data = "";

    //url拼接
    String lasturl = this.hostPort + path + urlParam;
    try {
      URL restURL = java.net.URI.create(lasturl).toURL();
      HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
      conn.setRequestMethod("POST");
      //请求头
      conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
      conn.setDoOutput(true);

      //输入流
      //OutputStream os = conn.getOutputStream();
      //解决中文乱码
      OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      os.write(param);
      os.flush();
      // 输出response code
      responseCode = conn.getResponseCode();
      // 输出response
      if (responseCode == 200) {
        //输出流
        //BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        //解决中文乱码
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        //data = reader.readLine();

        //解决返回参数换行问题，一次读一行，读入null时文件结束
        int line = 1;
        String tempString = null;
        while ((tempString = reader.readLine()) != null) {
          data += tempString;
          //把当前行号显示出来
          //System.out.println("line " + line + ": " + tempString);
          line++;
        }
        reader.close();

      } else {
        data = "false";
      }
      // 断开连接
      os.close();
      conn.disconnect();

    } catch (Exception e) {
      e.printStackTrace();
    }

    return data;
  }

  public static void main(String[] args) {
    //接口路径
    String pathGet = "/data/123";
    String pathPost = "/xxx/xxx/postFunction";

    System.out.println(pathGet);

    //get
    String paramGet = "?aaa=1&bbb=2";
    //RestCallerUtil为自行封装的工具类
    RestfulCaller rcuGet = new RestfulCaller("http://127.0.0.1:8000");
    String resultDataGet = rcuGet.restCallerGet(pathGet, paramGet);
    System.out.println(resultDataGet);

//    //post
//    String paramPost = "{'aaa':'1','bbb':'2'}";
//    //RestCallerUtil为自行封装的工具类
//    RestfulCaller rcuPost = new RestfulCaller("http://127.0.0.1:8000/");
//    String resultDataPost = rcuPost.restCallerPost(pathPost, paramPost);
//    System.out.println(resultDataPost);

  }
}
